﻿#include "UCarouselManager.h"
#include <QMenu>
#include <QDir>
#include <QString>
#include <QInputDialog>
#include <QMessageBox>
#include <QRegularExpression>
#include "Global.h"
#include "UToolBarManager.h"
#include "CLoadFromConfig.h"
UCarouselManager::UCarouselManager(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	g_pRootCarouse = NULL;
	m_pNodeCurr = nullptr;
}

UCarouselManager::~UCarouselManager()
{}

void UCarouselManager::setCarouseWidget(UCarousePage * pWidget)
{
	m_pCarouseWidget = pWidget;
}

void UCarouselManager::addNode(CBaseCarouse * parent)
{
	slot_addNode();
}

void UCarouselManager::addPage(CBaseCarouse * parent)
{
}

void UCarouselManager::deleteNode(CBaseCarouse * node)
{
	slot_deleteNode();
}

void UCarouselManager::initUi()
{
	ui.treeView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.treeView->setSelectionMode(QAbstractItemView::SingleSelection);
	ui.treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);  // 禁用编辑
	//ui.treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); // 支持 Ctrl 和 Shift 多选
	ui.treeView->header()->hide();
	model = new QStandardItemModel(this);
	ui.treeView->setModel(model);
	ui.treeView->setContextMenuPolicy(Qt::CustomContextMenu);
	ui.treeView->viewport()->installEventFilter(this);
	ui.treeView->setDragDropMode(QAbstractItemView::DropOnly);  // ✅ 设置为 drop-only 模式
	ui.toolButton->setIcon(QIcon(":/SmartControl/Resource/toolbar/add_2.png"));
	ui.toolButton_2->setIcon(QIcon(":/SmartControl/Resource/toolbar/delete_2.png"));
	ui.toolButton->setIconSize(QSize(30, 30));
	ui.toolButton_2->setIconSize(QSize(30, 30));
	ui.toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
	ui.toolButton_2->setToolButtonStyle(Qt::ToolButtonIconOnly);
	connect(ui.toolButton, SIGNAL(clicked()), this, SLOT(slot_addNode()));
	connect(ui.toolButton_2, SIGNAL(clicked()), this, SLOT(slot_deleteNode()));
	connectTree();
	QString exePath = QCoreApplication::applicationDirPath();
	// 构建配置文件的完整路径
	QString configFilePath = QDir(exePath).filePath("carouse.xml");
	QAction *pAdd = g_pToolBarMang->addAction(UToolBarManager::Carouse, A2T("添加节点"), QIcon(":/SmartControl/Resource/toolbar/add.png"));
	QAction *pDelete = g_pToolBarMang->addAction(UToolBarManager::Carouse, A2T("删除设备"), QIcon(":/SmartControl/Resource/toolbar/delete.png"));
	QAction *pSet = g_pToolBarMang->addAction(UToolBarManager::Carouse, A2T("设置轮播间隔"), QIcon(":/SmartControl/Resource/toolbar/set.png"));
	g_pToolBarMang->addSeparator(UToolBarManager::Carouse);
	QAction *pRun = g_pToolBarMang->addAction(UToolBarManager::Carouse, A2T("开始轮播"), QIcon(":/SmartControl/Resource/toolbar/run.png"));
	/*QAction *pStop = g_pToolBarMang->addAction(UToolBarManager::Carousel, A2T("停止轮播"), QIcon(":/SmartControl/Resource/toolbar/stop.png"));
	QAction *pEnlarge = g_pToolBarMang->addAction(UToolBarManager::Carousel, A2T("全屏"), QIcon(":/SmartControl/Resource/toolbar/Enlarge.png"));*/
	g_pToolBarMang->addSeparator(UToolBarManager::Carouse);
	connect(pAdd, &QAction::triggered, this, &UCarouselManager::slot_addNode);
	connect(pDelete, &QAction::triggered, this, &UCarouselManager::slot_deleteNode);
	connect(pSet, &QAction::triggered, this, &UCarouselManager::slot_setInterval);
	connect(pRun, &QAction::triggered, this, &UCarouselManager::slot_runCarouse);
	/*connect(pStop, &QAction::triggered, this, &UCarouselManager::slot_stopCarouse);
	connect(pEnlarge, &QAction::triggered, this, &UCarouselManager::slot_enlarge);*/
}


void UCarouselManager::createNullMenu(const QPoint& globalPos)
{
	QMenu* menu = new QMenu(this);

	if (m_pNodeCurr == nullptr)
	{
		m_pNodeCurr = g_pRootCarouse;
	}
	CBaseCarouse* node = m_pNodeCurr;
	if (m_pNodeCurr->getType() == CBaseCarouse::enRootCarouse)
	{
		menu->addAction(QIcon(":/SmartControl/Resource/toolbar/add.png"), A2T("添加节点(N)..."), this, [=]() { addNode(node); });		
	}
	else if (m_pNodeCurr->getType() == CBaseCarouse::enNodeCarouse)
	{
		//menu->addAction(A2T("添加子节点"), this, [=]() { addNode(node); });
		menu->addAction(A2T("设置组轮播间隔"), this, [=]() { slot_setInterval(); });
		menu->addAction(A2T("开始轮播"), this, [=]()
			{
				m_pNodeCurr = node;
				m_pCarouseWidget->setCurrNode(node);
				m_pCarouseWidget->enlargeUi(true);
				m_pCarouseWidget->ctrCarouse(true);

			});
		menu->addAction(A2T("停止轮播"), this, [=]() {m_pCarouseWidget->ctrCarouse(false); });
	}
	else
	{
		menu->addAction(A2T("删除"), this, [=]() { deleteNode(node); });
	}
	
	menu->exec(globalPos);
	delete menu;

}

void UCarouselManager::showContextMenu(CBaseCarouse * node, const QPoint & globalPos)
{
	QMenu* menu = new QMenu(this);
	// 通用菜单
	menu->addAction(A2T("重命名"), this, [this, node]() { renameNode(node); });

	// 删除操作
	switch (node->getType()) {
	case CBaseCarouse::enRootCarouse:
		menu->addAction(A2T("添加子节点"), this, [=]() { addNode(node); });
		//menu->addAction(A2T("设置组轮播间隔"), this, [=]() { slot_setInterval(); });
	/*	menu->addAction(A2T("开始轮播"), this, [=]() 
		{
			m_pNodeCurr = node;
			m_pCarouseWidget->setCurrNode(node);
			m_pCarouseWidget->enlargeUi(true);
			m_pCarouseWidget->ctrCarouse(true);
			
		});*/
		menu->addAction(A2T("停止轮播"), this, [=]() {m_pCarouseWidget->ctrCarouse(false); });
		break;
	case CBaseCarouse::enNodeCarouse:
		//menu->addAction(A2T("添加子节点"), this, [=]() { addNode(node); });
		menu->addAction(A2T("删除"), this, [=]() { deleteNode(node);  });
		menu->addAction(A2T("设置组轮播间隔"), this, [=]() { slot_setInterval(); });
		menu->addAction(A2T("开始轮播"), this, [=]()
		{
			m_pNodeCurr = node;
			m_pCarouseWidget->setCurrNode(node);
			m_pCarouseWidget->enlargeUi(true);
			m_pCarouseWidget->ctrCarouse(true);		

		});
		menu->addAction(A2T("停止轮播"), this, [=]() {m_pCarouseWidget->ctrCarouse(false); });
		break;
	case CBaseCarouse::enPageCarouse:
		menu->addAction(A2T("删除"), this, [=]() { deleteNode(node); });
		break;
	default:
		break;
	}
	menu->exec(globalPos);
	delete menu;
}

void UCarouselManager::showContextLeft(CBaseCarouse * node)
{
	CLoadFromConfig::saveToConfig();
	switch (node->getType())
	{
	case CBaseCarouse::enPageCarouse:
		m_pNodeCurr = node;
		m_pCarouseWidget->setCurrNode((CBaseCarouse*)node);
		break;
	case CBaseCarouse::enNodeCarouse:
		m_pNodeCurr = node;
		m_pCarouseWidget->setCurrNode((CBaseCarouse*)node);
		break;
	default:
		m_pNodeCurr = node;
		break;
	}
}

void UCarouselManager::connectTree()
{
	qRegisterMetaType<SPageItem>("SPageItem");
	ui.treeView->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(ui.treeView, &QTreeView::customContextMenuRequested, this, &UCarouselManager::onTreeContextMenuRequested);
	connect(ui.treeView, &UDropTreeView::sign_addItem, this, &UCarouselManager::slot_refushNode);
}

void UCarouselManager::slot_setInterval()
{
	QString text = showGetText(this, A2T("设置轮播间隔"), A2T("请输入轮播间隔时间单位秒:"),QString::number(m_pCarouseWidget->getInterval()));
	if (text.isEmpty())
	{
		showMessageBox(this, A2T("格式错误"), QString(A2T("请输入一个正确的时间间隔单位秒")), 1);
		return;
	}
	QRegularExpression re("^[1-9]\\d*$");  // 非0开头，纯数字
	bool isPositiveInteger = re.match(text).hasMatch();
	if (!isPositiveInteger) 
	{
		showMessageBox(this, A2T("格式错误"), QString(A2T("'%1' 不是有效正整数，请重新设置。")).arg(text),1);
		return;
	}
	m_pCarouseWidget->setInterval(text.toInt());
}

void UCarouselManager::slot_enlarge()
{
	m_pCarouseWidget->enlargeUi(true);
}

void UCarouselManager::slot_refushNode(CBaseCarouse * pNode)
{
	m_pCarouseWidget->setCurrNode(pNode,true);
}

bool UCarouselManager::eventFilter(QObject * obj, QEvent * event)
{
	if (obj == ui.treeView->viewport() && event->type() == QEvent::MouseButtonPress)
	{
		QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);

		if (mouseEvent->button() == Qt::LeftButton)
		{
			onTreeLeftClieck(mouseEvent->pos());
		}
	}

	return QObject::eventFilter(obj, event); // 交给默认处理
}

void UCarouselManager::onTreeLeftClieck(const QPoint & pos)
{
	emit sign_Show(1);
	QModelIndex index = ui.treeView->indexAt(pos);
	if (!index.isValid())
	{
		refushMenu();
		return;
	}
	QStandardItem* item = model->itemFromIndex(index);
	if (!item)
	{
		refushMenu();
		return;
	}

	CBaseCarouse* node = reinterpret_cast<CBaseCarouse*>(item->data(Qt::UserRole).value<void*>());
	if (!node)
	{
		refushMenu();
		return;
	}
	showContextLeft(node);
	refushMenu();
}

void UCarouselManager::slot_addNode()
{
	if (m_pNodeCurr == NULL)
	{
		m_pNodeCurr = g_pRootCarouse;
	}
	else
	{
		if (m_pNodeCurr->getType() != CBaseCarouse::enRootCarouse)
		{
			showMessageBox(this, A2T("警告"), A2T("此节点不允许添加子节点"), 1);
			return;
		}
	}
	QString sNodeName ="#" + QString::number(m_pNodeCurr->getChildren().size() + 1) + A2T("节点");
	QString sStr = showGetText(this, A2T("添加节点"), A2T("请输入节点名称"), sNodeName);
	if (!sStr.isEmpty())
	{
		
		CNodeCarouse* node = new CNodeCarouse(sStr, m_pNodeCurr);
		m_pNodeCurr = node;
		showContextLeft(node);
		refushMenu();
		//m_pNodeCurr->showItem(ui.treeView);
	}
}

void UCarouselManager::slot_addPage(SPageItem item)
{
}

void UCarouselManager::renameNode(CBaseCarouse * node)
{
	if (!node) return;

	QStandardItem* item = node->getItem();
	if (!item) return;

	// 允许临时编辑
	ui.treeView->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed);

	QModelIndex index = item->index();
	ui.treeView->edit(index);
	// 防止多次连接 itemChanged（避免重复触发）
	static QMetaObject::Connection conn;
	if (conn) QObject::disconnect(conn);
	// 监听编辑完成后恢复禁止编辑
	conn = connect(model, &QStandardItemModel::itemChanged, this, [=](QStandardItem* changedItem)
	{
		if (changedItem == item)
		{
			node->setName(item->text());  // 同步修改到 node
			QString newName = item->text();
			ui.treeView->setEditTriggers(QAbstractItemView::NoEditTriggers); // 编辑完成后再次禁用
			QObject::disconnect(conn); // 编辑完后断开连接

		}
	});
}

void UCarouselManager::slot_deleteNode()
{
	if (m_pNodeCurr == nullptr)
	{
		showMessageBox(this, A2T("警告"), A2T("请先选择节点或界面"), 1);
		return;
	}
	if (m_pNodeCurr == g_pRootCarouse)
	{
		showMessageBox(this, A2T("警告"), A2T("根节点不允许删除"), 1);
		return;
	}
	bool bSure= showMessageBox(this, A2T("提示"), A2T("确认删除此节点或者界面吗？"), 1,true);
	if (bSure)
	{
		CBaseCarouse* pParrent = (CBaseCarouse*)m_pNodeCurr->getParent();
		int index = pParrent->getChildren().indexOf(m_pNodeCurr);
		pParrent->removeChild(m_pNodeCurr);
		m_pNodeCurr = pParrent;
		showContextLeft(m_pNodeCurr);
		refushMenu();
	}
}

void UCarouselManager::slot_runCarouse()
{
	if (m_pNodeCurr != NULL)
	{
		m_pCarouseWidget->setCurrNode(m_pNodeCurr);
		m_pCarouseWidget->enlargeUi(true);
		m_pCarouseWidget->ctrCarouse(true);
	}
	else
	{
		showMessageBox(this, A2T("警告"), A2T("请先选择轮播组"), 1);
	}
	
}

void UCarouselManager::slot_stopCarouse()
{
	m_pCarouseWidget->ctrCarouse(false);
}

void UCarouselManager::onTreeContextMenuRequested(const QPoint & pos)
{
	emit sign_Show(1);
	QModelIndex index = ui.treeView->indexAt(pos);
	if (!index.isValid())
	{
		if (m_pNodeCurr == nullptr)
		{
			m_pNodeCurr = g_pRootCarouse;
		}
		showContextMenu(m_pNodeCurr, ui.treeView->viewport()->mapToGlobal(pos));
		refushMenu();
		return;
	}
	QStandardItem* item = model->itemFromIndex(index);
	if (!item)
	{
		refushMenu();
		return;
	}

	CBaseCarouse* node = reinterpret_cast<CBaseCarouse*>(item->data(Qt::UserRole).value<void*>());
	if (!node)
	{
		refushMenu();
		return;
	}
	m_pNodeCurr = node;
	showContextMenu(node, ui.treeView->viewport()->mapToGlobal(pos));
	refushMenu();
}


void UCarouselManager::refushUi()
{
	model->removeRow(0);
	model->appendRow(g_pRootCarouse->getItem());
	QModelIndex index = g_pRootCarouse->getItem()->index(); // 获取该 item 对应的 QModelIndex
	ui.treeView->expand(index);
	m_pNodeCurr = g_pRootCarouse;
}

void UCarouselManager::refushMenu()
{
	if (m_pNodeCurr == nullptr)
	{
		m_pNodeCurr = g_pRootCarouse;
	}
	m_pNodeCurr->showItem(ui.treeView);
	if (m_pNodeCurr->getType() == CBaseCarouse::enRootCarouse)
	{
		g_pToolBarMang->setToolBtn(UToolBarManager::Carouse, 1);
	}
	else
	{
		g_pToolBarMang->setToolBtn(UToolBarManager::Carouse, 0);
	}
}